import pyglet

class Button(object):
    HIDDEN=0
    ACTIVE=1
    INACTIVE=2
    PRESSED=2
    
    def __init__(self,iParent,iPos,iImgName,iCallBack):
        self.position=iPos
        self.parent=iParent
        
        self.callback=iCallBack
        self.oldStatus=self.INACTIVE
        self.status=Button.ACTIVE
        self.isPressed=False
        
     
        
        self.images=[None,]
        self.images.append(pyglet.resource.image(iImgName+"_on.png"))
        self.images.append(pyglet.resource.image(iImgName+"_off.png"))
        self.size=(self.images[1].width,self.images[1].height)
        
        for img in self.images:
            if img:
                img.anchor_x = img.width // 2
                img.anchor_y = img.height // 2
            
##        backColors=[
##            (255,255,255, 255),
##            (128, 255, 0, 255),
##            (128, 0, 255, 255)
##            ]
##            
##        for i in range(len(self.backColors)):
##            c=backColors[i]
##            
##            img=pyglet.image.SolidColorImagePattern(c).create_image(*iSize)
##            
##                  
##            self.images.append(img)

    
        
    def isPosIn(self,pos):
        
        xa,ya=pos
        x,y=self.position
        w,h=self.size
        
        if abs(x-xa)<w//2 and abs(y-ya)<h//2 :
            return True
        return False
    
    def on_mouse_press(self, x, y, button, modifiers):
        
        if self.isPosIn((x,y)):
            self.oldStatus=self.status
            if self.oldStatus==Button.INACTIVE:
                self.status=Button.ACTIVE
            else :
                self.status=Button.INACTIVE

            self.isPressed=True
            return True
        return False
    
    def on_mouse_release(self,x,y,button,modifiers):
        if (self.isPressed):
            self.callback()
        self.isPressed=False
        

    
    def draw(self):
        if self.status==Button.HIDDEN:
            return

        if self.isPressed:
            self.images[Button.PRESSED].blit(*self.position)
        else :      
            self.images[self.status].blit(*self.position)
        
                    
